<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;


class PlayerRole extends  Model{

    protected $table='player_info';
    protected static $fields_arr = ['player_id', 'account', 'area', 'player_name','udid', 'user_type'
    ,'photo', 'exp', 'level', 'vip_level', 'vip_exp', 'hero_id','hero_skin_id','guild_id','pet_id'
    ,'default_mount_id', 'mount_id', 'thew','gold','diamond','ticket','online_time','login_time','create_time'];

    public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        //$data = \DB::connection($this->selectdb())->table($tableAccount)->skip($page* $perPage)->take($perPage)->get();
        //$data = $data->toArray();
        $rw = \DB::connection('mysql_bgac')->table('player_info')->select(\DB::raw(implode(',', self::$fields_arr)));
        self::SourceCondition($rw);
        $total = $rw->get()->count();
        $rw->orderBy('player_id', "DESC");
        $rw->skip($start)->take($perPage);
        $data =  $rw->get();
        $data = $data->toArray();

        \Log::debug(__METHOD__, [$rw->toSql()]);
        // $data = json_decode($data, true);
        self::convItemList($data);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function getItemIdByHero($hero_id) {
        return $hero_id - (100000000-6000000);
    }
    public static function convItemList(&$list) {
        $item_model = New \App\Models\Item\Item();
        $item_alias_arr = $item_model->GetItemArray(0, true);
        foreach ($list as $obj) {
            // \Log::debug("[PLAYER][ROLE][CONV]", [$obj->hero_id]);
            
            $alias = $item_alias_arr[self::getItemIdByHero($obj->hero_id)] ?:[];
            $obj->hero_alias = $alias['name'];
        }
    }

    public static function with($relations)
    {
        return new static;
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();

        if ($cond['player_id']){
            if (is_array($cond['player_id'])) {
                $pids = $cond['player_id'];
            } else {
                $pids = explode(',', $cond['player_id']);
            }
            $rw->whereIn("player_id", $pids);
        }

        if ($cond['account']){
            $rw->where("account", $cond['account']);
        }

        if ($cond['player_name']){
            $rw->where("player_name", 'like', '%'.$cond['player_name'].'%');
        }

        // \Log::debug('[PLAYER][BEHAVIOR][COND]', [$cond['op_module']]);

        if ($cond['area']){
            $rw->whereIn("area", $cond['area']);
        }



        if (is_array($cond['create_time'])) {
            $start = \App\ModelStatistic\StatisticCommon::GetIntTime($cond['create_time']['start']) ?: 0;
            $rw->where("create_time", ">", $start);
            $end = \App\ModelStatistic\StatisticCommon::GetIntTime($cond['create_time']['end']) ?: 0;
            if ($end) {
                $rw->where("create_time", "<", $end);
            }
        }

        if ($cond['_sort']) {
            $rw->orderby($cond['_sort']['column'], $cond['_sort']['type']);
        }
    }

    // 
    public static function syncPlayFromGame($area) {
        if (empty ($area) ) {
            return false;
        }
        \Log::debug("[COMMAND][SYNC_PLAYERS]area[". $area.']');
        \App\Models\Area::RemoteBgsiSelectByArea($area);
        \Config::set("database.connections.remote_bgsi.database", 'game_db_'.$area);

        $page = $count = 0;
        do {
            $count = self::getRemotePlayerLists($page, 100);
        }while($count > 0);
        return true;
    }

    public static function getRemotePlayerLists(&$skip_page, $per_page) {
        !$per_page  && $per_page = 100;
        $start = $skip_page  * $per_page;
        $skip_page++;
        // 这里实际查的是 game db 库
        $list = \DB::connection('remote_bgsi')->table('player_info')->where('account', '>', 30000)
        -> skip($start)->take($per_page)
        ->get()
        ->toArray();
        $count = 0;

        
        $fields_str = implode(',', self::$fields_arr);
        $sql = 'replace into tb_player_info('.$fields_str.') values ';
        $col_empty = array_flip(self::$fields_arr);
        foreach ($list as $obj) {
            $col = $col_empty;
            foreach ($obj as $attr =>$value) {
                if (! in_array($attr, self::$fields_arr)) {
                    continue;
                }
                $col[$attr] = "'". str_replace("'","\'",$value). "'";
            }
            $col_str = '(' .implode(',', $col). '),';
            $sql .= $col_str;
            $count ++;
        }
        $sql = substr($sql, 0, -1) . ';';
        if ($count == 0) {
            return $count;
        }
        \Log::debug("[COMMAND][SYNC_PLAYERS]count[". $count.']');
        
        $db = \DB::reconnect('mysql_bgac');
        $db->getPdo()->exec($sql);
        return $count;
    }

}